package cc.dowell.controller;

import cc.dowell.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${custom-setting.file-path.root}")
    private String rootPath;

    @Value("${custom-setting.file-path.img-upload}")
    String imgUploadPath;

    @PostMapping("/upload")
    public R<String> upload(@RequestParam(value = "file") MultipartFile file) {
        log.info("上传文件名{}", file.getOriginalFilename());
        // DateTime dateTime = DateUtil.date();
        // String uploadYearMonth = DateUtil.format(dateTime, "yyyyMM");
        // 如果按月保存 + uploadYearMonth + "/"
        //上传图片的保存路径
        String savePath = rootPath + imgUploadPath;
        log.info("上传到路径{}", savePath);
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            savePathFile.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));  //.jpg
        String newFilename = UUID.randomUUID() + suffix;
        try {
            file.transferTo(new File(savePath + newFilename));
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("Err:图片上传失败");
        }
        //将文件名返回
        return R.success(newFilename);
    }

    @GetMapping("/download")
    public void download(String filename, HttpServletResponse response) {
        String savePath = rootPath + imgUploadPath;
        try {
            FileInputStream fis = new FileInputStream(savePath + filename);
            response.setContentType("image/jpeg");
            ServletOutputStream os = response.getOutputStream();
            int len = 0;
            byte[] buff = new byte[4096];
            while ((len = fis.read(buff)) != -1) {
                os.write(buff, 0, len);
            }
            fis.close();
            os.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
